package com.guet.controller.teacher;

import com.guet.DTO.UserLoginDTO;
import com.guet.Entity.User;
import com.guet.VO.UserLoginVO;
import com.guet.constant.JwtClaimsConstant;
import com.guet.properties.JwtProperties;
import com.guet.result.Result;
import com.guet.service.LoginService;
import com.guet.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController("teacherLoginController")
@RequestMapping("teacher/login")
@Slf4j
@CrossOrigin
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);
        User user = loginService.login(userLoginDTO);
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.ADMIN_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        UserLoginVO build = UserLoginVO.builder().id(user.getId()).
                identify(user.getIdentify()).
                token(token).build();

        return Result.success(build);
    }
}
